import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import { setHtmlPageLang, setLoadLocalePool } from "./helper";
import { store } from "@/redux";

function getModuleName(key: string) {
	if (!key) return "";
	if (!key.includes("/")) return key;
	let fileName = key.split("/").pop() || "";
	return fileName.substring(0, fileName.lastIndexOf("."));
}

function createI18nOptions() {
	const langModules = import.meta.globEager("./lang/*.ts");
	const { language } = store.getState().global;
	console.log("locale", language);

	let languageDict: Recordable = Object.keys(langModules).reduce((obj: Recordable, path: string) => {
		obj[getModuleName(path)] = {};
		return obj;
	}, {});
	Object.keys(langModules).forEach((key: string) => {
		languageDict[getModuleName(key)]["translation"] = langModules[key].default;
	});

	setHtmlPageLang(language);
	setLoadLocalePool(loadLocalePool => {
		loadLocalePool.push(language);
	});

	return {
		resources: languageDict,
		// default language
		fallbackLng: "en",
		debug: false,
		interpolation: {
			// not needed for react as it escapes by default
			escapeValue: false
		}
	};
}

i18n.use(initReactI18next).init(createI18nOptions());

export default i18n;
